/**
 * Created on 2007-05-23 13:48
 */
package tools.xmlTools;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * @author David Wallin
 * 
 * A wrapper class for xml document nodes
 */
public class XMLReadOnlyNode
{
	/**
	 * The wrapped Element
	 */
	private Element			m_Node;
	/**
	 * The name of this node
	 */
	private String			m_NodeName;
	/**
	 * The textual value of this node
	 */
	private String			m_NodeValue;
	
	/**
	 * Constructor, protected so only XMLDocument and this class can call it
	 */
	protected XMLReadOnlyNode(Element node)
	{
		m_Node = node;
		m_NodeName = m_Node.getNodeName();
		m_NodeValue = m_Node.getTextContent();
	}
	
	/**
	 * Gets the value at a certain node as a String
	 * 
	 * @param nodeName the name of the node to read
	 * @param occurrence what occurrence of the node name
	 * @return the value in the given node
	 */
	public String getValue(String nodeName, int occurrence)
	{
		String value = "";
		NodeList nodes = m_Node.getElementsByTagName(nodeName);
		
		if(nodes.getLength() > occurrence)
		{
			Node child = nodes.item(occurrence);
			
			if(child == null)
			{
				System.out.println("child was null: " + nodeName + ", " + occurrence);
			}
			
			value = child.getTextContent();
		}
		else
		{
			System.out.println("occurrence not found: " + nodeName + ", " + occurrence);
		}
		
		return value;
	}
	
	/**
	 * Gets the data in the given node
	 * 
	 * @param nodeName the name of the node to get the data from
	 * @param occurrence what occurrence of the node
	 * @return the data at the given node
	 */
	public XMLReadOnlyNode getNode(String nodeName, int occurrence)
	{
		XMLReadOnlyNode node = null;
		NodeList nodes = m_Node.getElementsByTagName(nodeName);
		
		if(nodes.getLength() > occurrence)
		{
			Node child = nodes.item(occurrence);
			node = new XMLReadOnlyNode((Element)child);
		}
		
		return node;
	}
	
	/**
	 * Gets the number of occurrences of a certain node name
	 * 
	 * @param nodeName
	 * @return the number of occurrences of the given node name
	 */
	public int getOccurrences(String nodeName)
	{
		return m_Node.getElementsByTagName(nodeName).getLength();
	}
	
	/**
	 * Gets the name of this node
	 * 
	 * @return the name of this node
	 */
	public String getNodeName()
	{
		return m_NodeName;
	}
	
	/**
	 * Gets the value of this node
	 * 
	 * @return the value of this node
	 */
	public String getNodeValue()
	{
		return m_NodeValue;
	}
	
	/**
	 * Gets the Element this XMLNode wrapps
	 * 
	 * @return the Element wrapped in this XMLNode instance
	 */
	public Element getElement()
	{
		return m_Node;
	}
}
